//
//  XDInfoDetailViewController.m
//  XDHoHo
//
//  Created by xie yajie on 13-11-17.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import "XDInfoDetailViewController.h"

#import <ShareSDK/ShareSDK.h>
#import "XDActivityModel.h"
#import "XDCommentModel.h"
#import "XDActivityView.h"
#import "XDInputView.h"
#import "UIImage+Category.h"

#define KINFO_COMMENT_HOT @"hotComment"
#define KINFO_COMMENT_DEFAULT @"defaultComment"

@interface XDInfoDetailViewController ()<UITableViewDataSource, UITableViewDelegate, XDActivityViewDelegate, UIAlertViewDelegate>
{
    NSMutableDictionary *_commentSource;
    XDActivityModel *_activityModel;
}

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) XDInputView *inputView;//底部评论工具

@end

@implementation XDInfoDetailViewController

- (id)initWithActivityModel:(XDActivityModel *)activityModel
{
    self = [super init];
    if (self) {
        // Custom initialization
        _commentSource = [NSMutableDictionary dictionary];
        _activityModel = activityModel;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    self.title = @"详情";
    [self.view addSubview:self.inputView];
    [self.view addSubview:self.tableView];
    
    [self requestDataForRefresh:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark - getting

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 44) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:240 / 255.0 blue:235 / 255.0 alpha:1.0];
    }
    
    return _tableView;
}

- (XDInputView *)inputView
{
    if (_inputView == nil) {
        _inputView = [[XDInputView alloc] initWithSuperView:self.view topView:self.tableView];
//        _inputView.delegate = self;
        _inputView.style = XDInputViewStyleBottom;
        _inputView.enableFaceKeyboard = YES;
        _inputView.textView.returnKeyType = UIReturnKeySend;
        _inputView.placeholder = @"说说你的想法";
        
//        UIImage *sendBGImage = [[UIImage imageNamed:@"area_send_bg"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) resizingMode:UIImageResizingModeStretch];
//        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 30.0)];
//        [rightButton setTitle:@"发送" forState:UIControlStateNormal];
//        [rightButton setBackgroundImage:sendBGImage forState:UIControlStateNormal];
//        [rightButton addTarget:self action:@selector(sendNewComment:) forControlEvents:UIControlEventTouchUpInside];
//        [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        _inputView.rightOuterView = rightButton;
    }
    
    return _inputView;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return [[_commentSource objectForKey:KINFO_COMMENT_HOT] count];
            break;
        case 2:
            return [[_commentSource objectForKey:KINFO_COMMENT_DEFAULT] count];
            break;
            
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"InfoCell";
    if (indexPath.section == 0) {
        CellIdentifier = @"InfoCell";
    }
    else{
        CellIdentifier = @"CommentCell";
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else{
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    
    if (indexPath.section == 0) {
        XDActivityView *activityView = [[XDActivityView alloc] initWithFrame:CGRectMake(10.0, 10.0, tableView.frame.size.width - 20, 0.0) activity:_activityModel];
        activityView.delegate = self;
        activityView.otherInfo = @{@"indexPath": indexPath};
        [activityView setupActivityView];
        [cell.contentView addSubview:activityView];
    }
    else{
        NSString *key = indexPath.section == 1 ? KINFO_COMMENT_HOT : KINFO_COMMENT_DEFAULT;
        XDCommentModel *model = [[_commentSource objectForKey:key] objectAtIndex:indexPath.row];
        
        XDActivityView *commentView = [[XDActivityView alloc] initWithFrame:CGRectMake(10.0, 1.0, tableView.frame.size.width - 20, 0.0) comment:model];
//        commentView.delegate = self;
//        commentView.userInfo = @{@"indexPath": indexPath};
        [commentView setupCommentView];
        [cell.contentView addSubview:commentView];
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && _activityModel) {
        XDActivityView *activityView = [[XDActivityView alloc] initWithFrame:CGRectMake(10.0, 10.0, tableView.frame.size.width - 20, 0.0) activity:_activityModel];
        return [activityView activityViewHeight] + 10;
    }
    else if (indexPath.section != 0)
    {
        NSString *key = indexPath.section == 1 ? KINFO_COMMENT_HOT : KINFO_COMMENT_DEFAULT;
        XDCommentModel *model = [[_commentSource objectForKey:key] objectAtIndex:indexPath.row];
        
        if (model) {
            XDActivityView *activityView = [[XDActivityView alloc] initWithFrame:CGRectMake(10.0, 1.0, tableView.frame.size.width - 20, 0.0) comment:model];
            return [activityView commentViewHeight] + 1;
        }
    }
    
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 0;
            break;
            
        default:
            return 30.0;
            break;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section != 0) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 30.0)];
        headerView.backgroundColor = [UIColor clearColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, headerView.frame.size.width - 20, 20.0)];
        label.backgroundColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:13.0];
        label.text = section == 1 ? @"热门评论" : @"最新评论";
        [headerView addSubview:label];
        
        return headerView;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

#pragma mark - XDActivityViewDelegate

//点击分享按钮
- (void)contactActivityViewShareButtonClicked:(XDActivityView *)activityView
{
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"这是一条测试信息"
                                       defaultContent:@""
                                                image:nil/*[ShareSDK imageWithPath:imagePath]*/
                                                title:@"ShareSDK"
                                                  url:@"http://www.sharesdk.cn"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    ///////////////////////
    //以下信息为特定平台需要定义分享内容，如果不需要可省略下面的添加方法
    
    //定制人人网信息
    [publishContent addRenRenUnitWithName:@"Hello 人人网"
                              description:INHERIT_VALUE
                                      url:INHERIT_VALUE
                                  message:INHERIT_VALUE
                                    image:INHERIT_VALUE
                                  caption:nil];
    
    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    
    id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:@"内容分享"
                                                              oneKeyShareList:[NSArray defaultOneKeyShareList]
                                                               qqButtonHidden:YES
                                                        wxSessionButtonHidden:YES
                                                       wxTimelineButtonHidden:YES
                                                         showKeyboardOnAppear:NO
                                                            shareViewDelegate:nil
                                                          friendsViewDelegate:nil
                                                        picViewerViewDelegate:nil];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:shareOptions
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]);
                                }
                            }];
}

//点击赞按钮
- (void)contactActivityViewPraiseButtonClicked:(XDActivityView *)activityView
{
    
}

//点击踩按钮
- (void)contactActivityViewTrampleButtonClicked:(XDActivityView *)activityView
{
    
}

//点击收藏按钮
- (void)contactActivityViewFavoriteButtonClicked:(XDActivityView *)activityView
{
    //判断是否登录
    //????
    
    //如果未登录
    UIAlertView *logoutAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功！登录后收藏的内容永久保存，换手机也照样找回来" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:@"现在登录", nil];
    [logoutAlertView show];
    
    //如果登录了
    //    UIAlertView *loginAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功！收藏的内容永久保存，换手机也照样找回来" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        //
    }
}

#pragma mark - button/item action

- (void)sendNewComment:(id)sender
{
    
}

#pragma mark - data

- (void)requestDataForRefresh:(BOOL)isRefresh
{
    if (isRefresh) {
        [_commentSource removeAllObjects];
    }
    else{
        
    }
    
    //测试数据
    NSDictionary *c1 = [NSDictionary dictionaryWithObjectsAndKeys:@"xieyajie1", KMODEL_NAME, [NSDate date], KMODEL_CREATEDATE, @"登录后收藏的内容永久保存，换手机也照样找回来", KMODEL_CONTENT, nil];
    XDCommentModel *cm1 = [[XDCommentModel alloc] initWithDictionary:c1];
    NSDictionary *c2 = [NSDictionary dictionaryWithObjectsAndKeys:@"xieyajie2", KMODEL_NAME, [NSDate date], KMODEL_CREATEDATE, @"登录后收藏的内容永久保存，换手机也照样找回来", KMODEL_CONTENT, nil];
    XDCommentModel *cm2 = [[XDCommentModel alloc] initWithDictionary:c2];
    NSArray *hotComments = [NSArray arrayWithObjects:cm1, nil];
    NSArray *defaultComments = [NSArray arrayWithObjects:cm1, cm2, nil];
    [_commentSource setObject:hotComments forKey:KINFO_COMMENT_HOT];
    [_commentSource setObject:defaultComments forKey:KINFO_COMMENT_DEFAULT];
}

@end
